﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Rison.Web.Common;
using Rison.BusinessFacade.Helper;
using Rison.BusinessFacade.Common;
using Rison.BusinessFacade.Entity.ZP;
using Rison.BusinessFacade.Facade.ZP;
using Rison.DataAccess.Common;
using Rison.BusinessFacade.Facade.XT;
using Rison.BusinessFacade.Entity.NRBZ;
using Rison.BusinessFacade.Facade.NRBZ;
using System.IO;

namespace Rison.Web.ZP
{
    public partial class SelfExaminationDetail : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!string.IsNullOrEmpty(departid))
                {
                    ReLoadInformation();
                }
            }            
         }
       
        /// <summary>
        /// load 所有数据
        /// </summary>
         private void ReLoadInformation()
        {            
            LoadInfo();     
        }


        private void LoadInfo()
        {
            //string departid = departid;
            HiddentYear.Value = year;
            HiddenDepartID.Value = departid;
            SysUserFacade fa = new SysUserFacade();

            HiddenDepartName.Value = fa.GetDepartmentName(departid);
            //填报日期:
            LabTBRQ.Text ="填报日期：" + System.DateTime.Today.ToShortDateString();

            SelfExaminationFacade facade = new SelfExaminationFacade();
            DataRow dr = facade.GetInformation(departid,Convert.ToInt32(year));
            if (dr != null)
            {
                HiddenID.Value = dr["ID"].ToString();
                Hiddentotal.Value = dr["FieldTotal"].ToString();
                Hiddencurtotoal.Value = dr["FieldNum"].ToString();

                //部门
                this.txtCompanyName.Text =dr["CompanyName"].ToString() ;
                this.txtZGKS.Text = dr["ZGKS"].ToString();
                this.txtFGLD.Text = dr["FGLD"].ToString();
                this.txtFGLDTelephone.Text = dr["FGLDTelephone"].ToString();
                this.txtFGLDMobile.Text = dr["FGLDMobile"].ToString();
                this.txtFGLDEmail.Text = dr["FGLDEmail"].ToString();
                this.txtWZFZR.Text = dr["WZFZR"].ToString();
                this.txtWZFZRTelephone.Text = dr["WZFZRTelephone"].ToString();
                this.txtWZFZRMobile.Text = dr["WZFZRMobile"].ToString();
                this.txtWZFZREmail.Text = dr["WZFZREmail"].ToString();
                this.txtAQLLR.Text = dr["AQLLR"].ToString();
                this.txtAQLLRTelephone.Text = dr["AQLLRTelephone"].ToString();
                this.txtAQLLRMobile.Text = dr["AQLLRMobile"].ToString();
                this.txtAQLLREmail.Text = dr["AQLLREmail"].ToString();

                this.txtWebSite.Text = dr["WebSite"].ToString();
                this.txtWebFZR.Text = dr["WebFZR"].ToString();
                this.txtWebFZRTelephone.Text = dr["WebFZRTelephone"].ToString();
                this.txtWebFZRMobile.Text = dr["WebFZRMobile"].ToString();
                this.txtWebFZREmail.Text = dr["WebFZREmail"].ToString();
                this.txtWebTBR.Text = dr["WebTBR"].ToString();
                this.txtWebTBRTelephone.Text = dr["WebTBRTelephone"].ToString();
                this.txtWebTBRMobile.Text = dr["WebTBRMobile"].ToString();
                this.txtWebTBREmail.Text = dr["WebTBREmail"].ToString();
                this.rblZZRY.SelectedValue= dr["IfZZRY"].ToString();
                this.rblWebHosting.SelectedValue = dr["WebHosting"].ToString();
                this.txtWebHostingDes.Text = dr["WebHostingDes"].ToString();
                this.txtFirstDomain.Text = dr["FirstDomain"].ToString();
                this.txtRecordNum.Text = dr["RecordNum"].ToString();
                //if (this.txtFirstDomain.Text == "") this.txtFirstDomain.Attributes.Add("style", "display:none");
                this.rblIfYJYM.SelectedValue = (this.txtFirstDomain.Text == "") ? "0" : "1";
               

                this.txtSecondDomain.Text = dr["SecondDomain"].ToString();
                this.rblIFSubSite.SelectedValue = dr["IFSubSite"].ToString();
                if (!String.IsNullOrEmpty(dr["State"].ToString()))
                {
                    this.Hiddenstate.Value = dr["State"].ToString();
                }
                else
                {
                    this.Hiddenstate.Value = "0";
                }
                if(!String.IsNullOrEmpty(dr["LastModifiedTime"].ToString()))
                {
                    this.LabTBRQ.Text = "最后更新日期：" + dr["LastModifiedTime"].ToString();
                }
                

            }

            //Load 子网站
            LoadSubTable(facade);

            //Load 工作人员
            LoadTable(facade);
        }

        private string departid
        {
            get 
            { 
                if(!string.IsNullOrEmpty(Request.QueryString["DepartID"]) && CurrentLoginedUser.UserId!="")
                {
                   return Request.QueryString["DepartID"].ToString();
                }
                return "";
            }
        }

        private string year
        {
            get { return string.IsNullOrEmpty(Request.QueryString["year"]) ? System.DateTime.Today.Year.ToString() : Request.QueryString["year"]; }
        }

        private string userid
        {
            get { return CurrentLoginedUser.UserId; }
        }

        protected override string key
        {
            get
            {
                if (HiddenID.Value != "")
                {
                    return HiddenID.Value;
                }
                return "";
            }
        }

        private string state;
        

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("SelfExaminationView.aspx?DepartID="+departid);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //初始化
            string LabMesage = "";

            //验证
            if (departid == "")
            {
                LabMesage = "请选择部门！";
                return;
            }

            //保存
            SelfExaminationFacade facade = new SelfExaminationFacade();

            //List<SqlField> indexKeyFields = new List<SqlField>();
            //indexKeyFields.Add(new SqlField("ID", txtUserId.Text.Trim()));


            SelfExamination exam = null;
          
            if (HiddenID.Value != "")
                exam = facade.Retrieve("id",key) as SelfExamination;
            else
                exam = new SelfExamination();
            if ("1".Equals(exam.State))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('信息已经提交，不能再次修改');</script>");
                return;
            }

            if (HiddenID.Value != "")
                exam.ID = HiddenID.Value;
            else
                exam.ID = System.Guid.NewGuid().ToString();

            if (HiddentYear.Value!="")
                exam.Year =Convert.ToInt32(HiddentYear.Value);
            else
                exam.Year=System.DateTime.Today.Year;
           
            
            exam.DepartID = departid;
            exam.FieldTotal = Convert.ToInt16(this.Hiddentotal.Value);
            exam.FieldNum = Convert.ToInt16(this.Hiddencurtotoal.Value);
            exam.CompanyName = cleanDefaultValue(this.txtCompanyName.Text);
            exam.ZGKS = cleanDefaultValue(this.txtZGKS.Text);
            exam.FGLD = cleanDefaultValue(this.txtFGLD.Text);
            exam.FGLDTelephone=this.txtFGLDTelephone.Text;
            exam.FGLDMobile=this.txtFGLDMobile.Text;
            exam.FGLDEmail=this.txtFGLDEmail.Text;
            exam.WZFZR = cleanDefaultValue(this.txtWZFZR.Text);
            exam.WZFZRTelephone=this.txtWZFZRTelephone.Text;
            exam.WZFZRMobile=this.txtWZFZRMobile.Text;
            exam.WZFZREmail=this.txtWZFZREmail.Text;
            exam.AQLLR = cleanDefaultValue(this.txtAQLLR.Text);
            exam.AQLLRTelephone=this.txtAQLLRTelephone.Text;
            exam.AQLLRMobile=this.txtAQLLRMobile.Text;
            exam.AQLLREmail = this.txtAQLLREmail.Text;

            exam.WebSite = this.txtWebSite.Text;
            exam.WebFZR = this.txtWebFZR.Text;
            exam.WebFZRTelephone = this.txtWebFZRTelephone.Text;
            exam.WebFZRMobile = this.txtWebFZRMobile.Text;
            exam.WebFZREmail = this.txtWebFZREmail.Text;
            exam.WebTBR = this.txtWebTBR.Text;
            exam.WebTBRTelephone = this.txtWebTBRTelephone.Text;
            exam.WebTBRMobile = this.txtWebTBRMobile.Text;
            exam.WebTBREmail = this.txtWebTBREmail.Text;
            exam.IfZZRY = this.rblZZRY.SelectedValue;
            exam.WebHosting = this.rblWebHosting.SelectedValue;
            exam.IFSubSite = this.rblIFSubSite.SelectedValue;
            exam.WebHostingDes = cleanDefaultValue(this.txtWebHostingDes.Text);
            exam.FirstDomain = this.txtFirstDomain.Text;
            exam.RecordNum = this.txtRecordNum.Text;
            exam.SecondDomain = this.txtSecondDomain.Text;
            exam.State = state;
           
            long returnValue = 0;
            if (HiddenID.Value != "")
            {
                exam.LastModifiedTime = System.DateTime.Now.ToString();
                exam.LastModified = userid;
            
                returnValue = facade.Update(exam);

                if (returnValue < 0)
                {
                    LabMesage = "主表更新错误！";
                }

                LabMesage += subSave(facade);
            }
            else
            {
                exam.CreateTime = System.DateTime.Now.ToString();
                exam.Creator = userid;

                returnValue = facade.Save(exam);

                if (returnValue > 0)
                {
                    LabMesage = subSave(facade);
                }
                if (returnValue < 0)
                {
                    LabMesage = "保存错误！";
                }
            }
           // uploadFile();
            if (Request.Params["ajax"] == "true")
            {
                Response.Redirect(String.Format("SelfExaminationAjaxSave.ashx?id={0}&fieldTotal={1}&fieldNum={2}",exam.ID, exam.FieldTotal,exam.FieldNum));
            }
            if (LabMesage == "")
            {
                Response.Redirect("SelfExaminationDetail.aspx?DepartID=" + departid + "&type=1");
            }
            
        }

        protected void btnSumbit_Click(object sender, EventArgs e)
        {
            state = "1";
            btnSave_Click(sender, e);
        }

        private string subSave(SelfExaminationFacade facade)
        {
            string ErrorMessage = "";
            //1.子网站保存

            ErrorMessage += SaveSubTabel(facade);

            //2.工作人员权限保存            

            ErrorMessage += SaveGZRYList(facade);           

            //3.历史表更新
            ErrorMessage += HistorySave();

            return ErrorMessage;
        }

        #region "子网站 create/delete/update child website"
        private string SaveSubTabel(SelfExaminationFacade facade)
        {
            string info = HttpContext.Current.Request.Form["_subwebsite"];

            string msg = facade.SaveSubInfobyParentId(HiddenID.Value, info);
            return msg;

        }

        private void LoadSubTable(SelfExaminationFacade facade)
        {
            DataTable dt = facade.LoadSubInfobyParentId(HiddenID.Value);          
            if (dt == null || dt.Rows.Count == 0)
            {               
                DrawOneRow("tableSubWebSite", "_subwebsite", "", ""); //blank row                
            }
            else
            {              

                foreach (DataRow dr in dt.Rows)
                {
                    DrawOneRow("tableSubWebSite", "_subwebsite", dr["SubWebSite"].ToString(), dr["SubDomain"].ToString());
                }                              

            }
        }

        private void DrawOneRow(string t, string inputname, string p1, string p2)
        {
            if (inputname == null)
            {
                inputname = "http://";
            }

            HtmlTableRow tr = new HtmlTableRow();
            HtmlTableCell ce = new HtmlTableCell();

            tr = new HtmlTableRow();

            ce = new HtmlTableCell();
            ce.InnerHtml = "子网站名称";
            tr.Cells.Add(ce);

            ce = new HtmlTableCell();
            ce.InnerHtml = "<input type='text' name='" + inputname + "' value='" + p1 + "' style='width:191px;' class='Text' />";
            tr.Cells.Add(ce);

            ce = new HtmlTableCell();
            ce.InnerHtml = "域名";
            tr.Cells.Add(ce);

            ce = new HtmlTableCell();
            ce.InnerHtml = "<input type='text' name='" + inputname + "' value='" + p2 + "' style='width:300px;' class='Text'/>";
            tr.Cells.Add(ce);
            HtmlTable ht = (HtmlTable)this.Page.Controls[0].FindControl(t);
            ce = new HtmlTableCell();
            if (ht.Rows.Count > 0)
            {
                ce.InnerHtml = "<img alt='删除' src='../style/images/_-.gif' onclick='removeParentNode(this);' class='img'/>";
            }
            else
            {
                ce.InnerHtml = "&nbsp;";
            }
            tr.Cells.Add(ce);

            ht.Rows.Add(tr);
        }
        #endregion

        #region "工作人员权限"
        private ArrayList EmployList
        {
            get
            {
                ArrayList al = new ArrayList();

                al.Add("新闻信息报送");
                al.Add("政府信息公开");
                al.Add("依申请公开受理");
                al.Add("行政审批");
                al.Add("信访受理");
                al.Add("在线咨询");
                al.Add("网站管理员");
                al.Add("公共服务");
                al.Add("其它信息发布");

                return al;
            }
        }
        private string SaveGZRYList(SelfExaminationFacade facade)
        {
            List<EmployeeField> employees = new List<EmployeeField>();
            string info = "";

            for (int i = 0; i < EmployList.Count; i++)
            {
                info = HttpContext.Current.Request.Form["_GZRY"+ (i+1).ToString()];
                employees.Add(new EmployeeField(EmployList[i].ToString(), info));
            }

            string msg= facade.SaveEmployeeFieldCollection(employees, HiddenID.Value);
            return msg;          

        }

        private void LoadTable(SelfExaminationFacade facade)
        {          
            DataTable dt = facade.LoadEmployeebyParentID(HiddenID.Value);
            int TableCount = EmployList.Count;
            if (dt == null || dt.Rows.Count == 0)
            {
                for (int i = 1; i <= TableCount; i++)
                {
                     DrawOneRow("tableGZRY"+i.ToString(), "_GZRY"+i.ToString(), "", "", "", ""); //blank row
                }               
            }
            else
            {
                for (int i = 0; i < TableCount; i++)
                {
                    DataRow[] drL = dt.Select("Type='" + EmployList[i].ToString () + "'");
                    if (drL == null || drL.Length == 0)
                    {
                        DrawOneRow("tableGZRY" + (i + 1).ToString(), "_GZRY" + (i + 1).ToString(), "", "", "", ""); //blank row
                    }
                    else
                    {
                        foreach (DataRow dr in drL)
                        {
                            DrawOneRow("tableGZRY" + (i + 1).ToString(), "_GZRY" + (i + 1).ToString(), dr["Name"].ToString(), dr["Telephone"].ToString(), dr["Mobile"].ToString(), dr["Email"].ToString());
                        }
                    }
                  }
               
            }            
        }

        private void DrawOneRow(string t,string inputname, string p1, string p2, string p3, string p4)
        {
            
            HtmlTableRow tr = new HtmlTableRow();
            HtmlTableCell ce = new HtmlTableCell();

            tr = new HtmlTableRow();

            ce = new HtmlTableCell();
            ce.InnerHtml = "<input type='text' name='" + inputname + "' value='" + p1 + "' style='width:50px' class='Text'/>";
            tr.Cells.Add(ce);

            ce = new HtmlTableCell();
            ce.InnerHtml = "固定电话";
            tr.Cells.Add(ce);

            ce = new HtmlTableCell();
            ce.InnerHtml = "<input type='text' name='" + inputname + "' value='" + p2 + "' style='width:129px' class='Text'/>";
            tr.Cells.Add(ce);

            ce = new HtmlTableCell();
            ce.InnerHtml = "手机";
            tr.Cells.Add(ce);

            ce = new HtmlTableCell();
            ce.InnerHtml = "<input type='text' name='" + inputname + "' value='" + p3 + "' style='width:140px' class='Text'/>";
            tr.Cells.Add(ce);

            ce = new HtmlTableCell();
            ce.InnerHtml = "邮箱";
            tr.Cells.Add(ce);
            if (p4 == null || "".Equals(p4.Trim()))
            {
                p4 = "@vip.changning.sh.cn";
            }
            ce = new HtmlTableCell();
            ce.InnerHtml = "<input type='text' name='" + inputname + "' value='" + p4 + "' style='width:250px' class='Text'/>";
            tr.Cells.Add(ce);

            HtmlTable ht = (HtmlTable)this.Page.Controls[0].FindControl(t);
            ce = new HtmlTableCell();
            if (ht.Rows.Count > 0)
            {
                ce.InnerHtml = "<img alt='删除' src='../style/images/_-.gif' onclick='removeParentNode(this);' class='img'/>";
            }
            else
            {
                ce.InnerHtml = "&nbsp;";
            }
            tr.Cells.Add(ce);

            ht.Rows.Add(tr);
        }
        #endregion

        #region "历史表更新"

        private string HistorySave()
        {
            HistoryExam hisexam = new HistoryExam();
            HistoryExamFacade facade = new HistoryExamFacade();
            hisexam.ID = System.Guid.NewGuid().ToString();
            hisexam.ExamID = HiddenID.Value;
            hisexam.Type = ExamType.网站基本信息填报.ToString();
            hisexam.Year = year;
            hisexam.DepartID = departid;
            hisexam.ModifiedID = this.userid;
            hisexam.ModifiedDate = System.DateTime.Now.ToString();

            int returnValue= facade.InsertHistory(hisexam);

            if (returnValue < 0)
                return "更新历史表报错！";

            return "";

        }
        #endregion

        #region "私有方法"
        private string cleanDefaultValue(string value)
        {
            if (value == "在此输入..." || value == "请文字说明...")
            {
                return "";
            }
            return value;
        }
        #endregion
        #region "upload"
        public string uploadFile()
        {
            string val = Request.Params["fileUploader8_hdnFileVal"];
            List<SysAttachment> _attachments = new List<SysAttachment>();
            int returnValue = -1;
            string del = "";

            NrbzFacade facade = new NrbzFacade();
            if (!string.IsNullOrEmpty(val))
            {
                _attachments = NewUpload(val);
                returnValue = facade.InsertAttachment(key, 8, _attachments);
            }

            del = Request.Params["fileUploader8_del"];
            if (!string.IsNullOrEmpty(del))
                returnValue = facade.DeleteAttachment(del);

            if (returnValue < 0)
            {
                return "文件上传成功，保存有误！";
            }

            return "";
        }
        #endregion
        public List<SysAttachment> NewUpload(string sFilePath)
        {

            List<SysAttachment> attList = new List<SysAttachment>();

            SysAttachment att = new SysAttachment();
            string[] a = sFilePath.Split(',');
            for (int i = 0; i < a.Length; i++)
            {
                string[] b = a[i].Split(';');
                if (b.Length > 1)
                {
                    string tmpVirtualPath = HttpContext.Current.Server.MapPath(b[0].ToString());
                    FileInfo f = new System.IO.FileInfo(tmpVirtualPath);
                    att = new SysAttachment();
                    att.FileName = b[1].ToString();
                    att.FilePath = f.Name;
                    att.FileSize = f.Length.ToString();
                    att.Extension = f.Extension;
                    attList.Add(att);

                    string fileName = HttpContext.Current.Server.MapPath(GlobalParams.Instance.AttachmentUploadUrl) + f.Name;
                    if (!File.Exists(fileName))
                    {
                        f.MoveTo(fileName);
                    }
                }
            }
            return attList;

        }
        public string UploadPath
        {
            get { return PageGlobalParams.PageUrlBase2 + GlobalParams.Instance.AttachmentUploadUrl; }
        }
    }

}
